package service.lqx.com.servicetest;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button startService = (Button) findViewById(R.id.start_service);
        Button stopService = (Button) findViewById(R.id.stop_service);
        final Button bindService = (Button) findViewById(R.id.bind_service);
        final Button unbindService = (Button) findViewById(R.id.unbind_service);
        final Intent startServiceIntent = new Intent(this, BackGroupService.class);
        final Intent intent = new Intent(this, ForegroundService.class);
        final Intent theIntentService = new Intent(this, TheIntentService.class);
        startService(theIntentService);//开启IntentService
        startService(intent);//开启前台服务
        startService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //启动服务
//                Log.e("Service","startService按钮被点击了");
                startService(startServiceIntent);
            }
        });
        stopService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //停止服务
                Log.e("Service","stopService按钮被点击了");
                stopService(startServiceIntent);
            }
        });

        bindService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Log.e("Service","bindService按钮被点击了");
                bindService(startServiceIntent,serviceConnection,BIND_AUTO_CREATE);
            }
        });

        unbindService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.e("Service","unbindService按钮被点击了");
                unbindService(serviceConnection);
            }
        });
    }
    /**
     * 创建ServiceConnection
     */
    final ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            //拿到后台服务代理对象
            final MyBind myBind = (MyBind) iBinder;
            myBind.startDownload();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
        }
    };
}
